<?php
/**
 * @todo  某些加密方法需要额外的参数
 * Class SimpleEncrypter
 */
class SimpleEncrypter
{

    /**
     * @var array
     */
    private static $supportCipherMethods;

    const DEFAULT_CIPHER_METHOD = 'AES-128-CBC';

    /**
     * 加密
     * @param string $str
     * @param string $key
     * @param string $iv
     * @param string $cipherMethod
     * @return string
     */
    public static function encrypt($str, $key, $iv = '0000000000000000', $cipherMethod = self::DEFAULT_CIPHER_METHOD)
    {
        return self::isSupportedCipherMethod($cipherMethod) ? openssl_encrypt($str, $cipherMethod, self::pad16($key), 0, self::padStr($iv, openssl_cipher_iv_length($cipherMethod))) : '';
    }

    /**
     * 解密
     * @param string $str
     * @param string $key
     * @param string $iv
     * @param string $cipherMethod
     * @return string
     */
    public static function decrypt($str, $key, $iv = '0000000000000000', $cipherMethod = self::DEFAULT_CIPHER_METHOD)
    {
        return self::isSupportedCipherMethod($cipherMethod) ? openssl_decrypt($str, $cipherMethod, self::pad16($key), 0, self::padStr($iv, openssl_cipher_iv_length($cipherMethod))) : '';
    }

    /**
     * @param string $str
     * @param int $length
     * @return bool|string
     */
    private static function padStr($str, $length, $padding = '0')
    {
        return strlen($str) < $length ? str_pad($str, $length, $padding) : substr($str, 0, $length);
    }

    /**
     * @param $method
     */
    private static function isSupportedCipherMethod($method)
    {
        if (self::$supportCipherMethods === null) {
             $tmpArr = openssl_get_cipher_methods(true);
            self::$supportCipherMethods = array_flip($tmpArr);
        }
        return $method && is_string($method) && array_key_exists($method, self::$supportCipherMethods);
        return $method && is_string($method) && isset(self::$supportCipherMethods[$method]);
    }
}
